package com.xiaoh.dormitoryrepairreportbackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.mapper.MaterialMapper;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.Material;
import com.xiaoh.dormitoryrepairreportbackend.service.MaterialService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物料表 服务实现类
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material>
        implements MaterialService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reduceStock(Integer materialId, Integer quantity) {
        Material material = this.getById(materialId);
        if (material == null) {
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST);
        }

        if (material.getStockCount() < quantity) {
            throw new BusinessException(ErrorCode.MATERIAL_STOCK_INSUFFICIENT);
        }

        material.setStockCount(material.getStockCount() - quantity);
        return this.updateById(material);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStock(Integer materialId, Integer quantity) {
        Material material = this.getById(materialId);
        if (material == null) {
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST);
        }

        material.setStockCount(material.getStockCount() + quantity);
        return this.updateById(material);
    }
}
